package edu.colorado.epmapp;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PorterDuff;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import edu.colorado.epmapp.form.PetForm;
import edu.colorado.epmapp.models.EPMDefs;
import edu.colorado.epmapp.models.EPMDefs.PetGender;
import edu.colorado.epmapp.models.EPMDefs.PetSize;
import edu.colorado.epmapp.models.EPMDefs.PetStatus;
import edu.colorado.epmapp.models.EPMDefs.PetType;
import edu.colorado.epmapp.models.User;
import edu.colorado.epmapp.network.OnResponseListener;

public class FormOneActivity extends Activity {
	
    private Spinner myStatusSpinner;
	private Spinner myGenderSpinner;
	private Spinner myPetTypeSpinner;
    private EditText myDescriptionText;
    private EditText myPetNameText;
    private EditText myContactNameText;
    private EditText myContactNumberText;
    
    private SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    private final String myCurrentDate = sdf.format(new Date());
    
    private LocationManager myLocationManager;
    private Double myGeoLat = 0.0;
    private Double myGeoLong = 0.0;
    private boolean myLocServiceDisabled = false;   
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_form_one);
        
        final Context context = this;
        
        myLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        
        myStatusSpinner = (Spinner) findViewById(R.id.statusSpinner);
    	myGenderSpinner = (Spinner) findViewById(R.id.genderSpinner);
    	myPetTypeSpinner = (Spinner) findViewById(R.id.petTypeSpinner);
        myDescriptionText = (EditText) findViewById(R.id.descriptionText);
        myPetNameText = (EditText) findViewById(R.id.descriptionText);
        myContactNameText = (EditText) findViewById(R.id.contactNameText);
        myContactNumberText = (EditText) findViewById(R.id.contactNumberText);
        
        InputFilter contactNameFilter = new InputFilter.LengthFilter(EPMDefs.USER_USERNAME_LENGTH);
        myContactNameText.setFilters(new InputFilter[]{contactNameFilter});
        
        InputFilter contactNumberFilter = new InputFilter.LengthFilter(EPMDefs.USER_USERNAME_LENGTH);
        myContactNumberText.setFilters(new InputFilter[]{contactNumberFilter});
        
        InputFilter petNameFilter = new InputFilter.LengthFilter(EPMDefs.PETREPORT_PET_NAME_LENGTH);
        myPetNameText.setFilters(new InputFilter[]{petNameFilter});
        
        InputFilter descFilter = new InputFilter.LengthFilter(EPMDefs.PETMATCH_DESCRIPTION_LENGTH);
        myDescriptionText.setFilters(new InputFilter[]{descFilter});
        
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.pet_types , android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        myPetTypeSpinner.setAdapter(adapter);
        
        adapter = ArrayAdapter.createFromResource(this,R.array.status_choices , android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        myStatusSpinner.setAdapter(adapter);
        
        adapter = ArrayAdapter.createFromResource(this,R.array.sex_choices , android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        myGenderSpinner.setAdapter(adapter);
        
        Button submitButton = (Button) findViewById(R.id.expressSubmitBtn);
        submitButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
        
        submitButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
        submitButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				PetForm form = new PetForm();
				
				fillPetForm(form);
				
				form.submitForm(new OnResponseListener() {
					
					public void onRequestComplete(String response) {
						
						boolean errorFlag = false;
						String titleText = "", msgText = "";
						
						if(response == null){
							errorFlag = true;
							titleText = "Sorry";
							msgText = "There may be a network problem. Please try again.";
						}
						else{
							if(response.contains(EPMDefs.CREATED)){

								Dialog submitDialog;
								submitDialog = new Dialog(context);
								submitDialog.setContentView(R.layout.submit_dialog);
								submitDialog.setTitle(R.string.form_submitted);
								submitDialog.setCancelable(false);

								Button submitAnotherBtn = 
									(Button) submitDialog.findViewById(R.id.submitAnotherBtn);
								submitAnotherBtn.setOnClickListener(new OnClickListener() {
									public void onClick(View v) {
										Intent formOneScreen = 
											new Intent(getApplicationContext(), FormOneActivity.class);
										startActivity(formOneScreen);
									}
								});
								submitDialog.show();
								
							}else if(response.contains(EPMDefs.BAD_REQUEST)){
								errorFlag = true;
								titleText = "Submit error";
								msgText = "Form incomplete, please complete and submit again.";
								
							}else if(response.contains(EPMDefs.UNAUTHORIZED)){
								errorFlag = true;
								titleText = "Submit error";
								msgText = "Please log back in and try again.";
								
							}else{
								errorFlag = true;
								titleText = "Sorry";
								msgText = "Your request cannot be completed at this time";
								//DEBUG
								msgText += " " + response;
							}
						} 
						
						if(errorFlag)
						{
							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
							alertDialogBuilder.setTitle(titleText);
							alertDialogBuilder.setMessage(msgText);
							alertDialogBuilder.setCancelable(true);
							alertDialogBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
			                    public void onClick(DialogInterface dialog, int which) {
			                    	dialog.cancel();
			                    }
			                });
							AlertDialog alert = alertDialogBuilder.create();
							alert.show();
						}
					}
				});
				
			}
		});
        
        Button nextPageBtn = (Button) findViewById(R.id.nextPageBtn);
        nextPageBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				PetForm form = new PetForm();
				fillPetForm(form);		
				User.getUser().setPetForm(form);
				
				Intent formTwoScreen = new Intent(getApplicationContext(), FormTwoActivity.class);
				startActivity(formTwoScreen);
			}
		});
        
        //
        // Camera Info
        //
        Button pictureBtn = (Button) findViewById(R.id.pictureBtn);
        
        PackageManager pm = getPackageManager();
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)){
        	pictureBtn.setEnabled(false);
        }else{
        	pictureBtn.setOnClickListener(new View.OnClickListener() {
    			public void onClick(View v) {
    				Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    			    startActivityForResult(takePictureIntent, 1);
    			}
    		});
        }
        
        //
        // Geo Location Info
        //
        final LocationListener locListener = new LocationListener() {

            public void onStatusChanged(String provider, int status, Bundle extras){
                if(status == LocationProvider.AVAILABLE){
                    myLocServiceDisabled = false;
                }
                else if(myGeoLat == 0.0 && myGeoLong == 0.0)
                {
                    myLocServiceDisabled = true;
                }
            }

            public void onProviderEnabled(String provider){
                myLocServiceDisabled = false;
            }

            public void onProviderDisabled(String provider){
                myLocServiceDisabled = true;
            }

            public void onLocationChanged(Location location) {
                myGeoLat = location.getLatitude();
                myGeoLong = location.getLongitude();
            }
        };

        myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                60000,          // 60-second interval.
                10,             // 10 meters.
                locListener);
    }
    
    @Override
	public void onBackPressed(){
		Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
		startActivity(loginScreen);
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    private void fillPetForm(PetForm form)
    {
    	//NOTE: form one has:status, pet type, gender, imageloc, curr loc, 
    	//      contact name, contact number, desc
		//NOTE: form two has: tag_id, micro_id, spayed/neutered, color, breed, 
    	//      size, loc lost
    	
    	//First fill out what Form One knows
    	form.setPetStatus(PetStatus.valueOf(myStatusSpinner.getSelectedItem().toString()));
		form.setPetType(PetType.valueOf(myPetTypeSpinner.getSelectedItem().toString()));
		form.setPetGender(PetGender.valueOf(myGenderSpinner.getSelectedItem().toString().substring(0, 1)));
		form.setPetDescription(myDescriptionText.getText().toString());
		form.setDate(myCurrentDate);
        form.setProposedBy(User.getUser().getUsername());
		   //TODO - Enhancement: Add a checkbox on view that tells us to populate
           //                    these fields with login info
		form.setContactName(myContactNameText.getText().toString());
		form.setContactNumber(myContactNumberText.getText().toString());
		   //TODO How to get image from camera intent?
		form.setImagePath("");
    	if(myLocServiceDisabled){		
		form.setGeoLocLat("");
		form.setGeoLocLong("");
    	}else{
    	    form.setGeoLocLat(myGeoLat.toString());
            form.setGeoLocLong(myGeoLong.toString());
    	}
		
		//Next fill out those fields Form Two will modify
		String[] sizeArr = getResources().getStringArray(R.array.size_choices);
		form.setPetSize(PetSize.valueOf(sizeArr[0].substring(0, 1)));
		form.setTagInfo("");
		form.setMicrochipId("");
		form.setSpayedOrNeutered("");
		form.setPetColor("");
		form.setPetBreed("");
		form.setLocation("");
		
		//Lastly fill out those fields neither form populates currently
		form.setPetName(myPetNameText.getText().toString());
		form.setPetAge("");
		/*form.setWorker("");
		form.setBookmarkedBy("");*/
    }
}
